package rsj.api.org.importdata;

import com.alibaba.excel.EasyExcelFactory;
import com.rlyy.aibase.utils.base.Box;
import com.rlyy.aibase.utils.base.MapNode;
import common.util.BoxUtil;
import common.util.http.HttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import rsj.api.org.entity.ImportFailedReason;
import rsj.api.org.entity.ImportTestDataEntity;
import rsj.api.org.entity.UploadFileParam;
import rsj.api.org.importdata.entity.ExecutionImportTestData;
import rsj.api.user.BaseLink;
import rsj.context.ApplicationContextUtil;
import rsj.properties.FileServiceProperties;
import common.util.validator.ParameterConversionCheck;

import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;

/**
 * 测试数据导入
 *
 * @author yuanqinglong
 * @since 2021/3/4 16:01
 */
@RestController
public class ImportTestDataController extends BaseLink {
    private static final Logger logger = LoggerFactory.getLogger(ImportTestDataController.class);

    /**
     * 测试数据导入
     *
     * @param box 参数
     * @return 结果
     */
    @Override
    @RequestMapping(name = "rsj_import_test_data")
    public Box executeLink(Box box) {
        UploadFileParam dataEntity = (UploadFileParam) ParameterConversionCheck.parameterConversionCheckFastFail(box, UploadFileParam.class);
        LocalDateTime importTime = this.performImportData(dataEntity);
        long importTimeLong = importTime.toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
        return BoxUtil.successBox(box).putMapNode("data", new MapNode().putNode("import_timestamp", String.valueOf(importTimeLong)));
    }


    /**
     * 执行数据导入
     *
     * @param uploadFileParam 参数（文件id、文件名称）
     * @return 查询本次导入结构失败的条件
     */
    private LocalDateTime performImportData(UploadFileParam uploadFileParam) {
        LocalDateTime importTime = LocalDateTime.now();
        this.analyseFile(this.downloadFilesFromFileServices(uploadFileParam), uploadFileParam, importTime);
        return importTime;
    }


    /**
     * 根据文件id从文件服务下载 文件
     *
     * @param uploadFileParam 参数
     * @return 文件输入流
     */
    private InputStream downloadFilesFromFileServices(UploadFileParam uploadFileParam) {
        String downloadUrl = ApplicationContextUtil.getBean(FileServiceProperties.class).getFileServiceDownloadUrl();
        //String devServiceUrl = PropUtils.getProperties("fileDevServiceDownloadUrl");
        return HttpUtil.fileDownload(downloadUrl, uploadFileParam.getFileId(), uploadFileParam.getFileName());
    }


    /**
     * 解析并保存测试数据
     *
     * @param inputStream     文件流
     * @param uploadFileParam 参数
     * @param importTime      导入时间
     */
    private void analyseFile(InputStream inputStream, UploadFileParam uploadFileParam, LocalDateTime importTime) {
        List<ImportFailedReason> failureData = new ArrayList<>();
        List<ImportTestDataEntity> successData = new ArrayList<>();
        try {
            EasyExcelFactory.read(inputStream).registerReadListener(new ImportEasyExcelInvoke(importTime, successData, failureData)).head(ImportTestDataEntity.class).doReadAll();
        } catch (Exception e) {
            logger.error("机构管理-测试导入解析失败原因：", e);
        } finally {
            this.saveData(failureData, successData, uploadFileParam);
        }
    }


    /**
     * 保存成功和失败的数据
     *
     * @param failureData            失败的数据
     * @param importTestDataEntities 解析成功的数据
     */
    private void saveData(List<ImportFailedReason> failureData, List<ImportTestDataEntity> importTestDataEntities, UploadFileParam uploadFileParam) {
        ExecutionImportTestData executionImportTestData = ApplicationContextUtil.getBean(ExecutionImportTestData.class);
        executionImportTestData.addImportFailedAndSuccessfullyData(importTestDataEntities, failureData, uploadFileParam);
    }


}
